 
package com.zdkj.subway.stm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.dto.in.SwMessageDTO;
import com.zdkj.subway.stm.dto.in.SwStInvoiceCheckDTO;
import com.zdkj.subway.stm.entity.SwParamLine;
import com.zdkj.subway.stm.entity.SwParamStation;
import com.zdkj.subway.stm.entity.SwStInvoiceCatCheck;
import com.zdkj.subway.stm.entity.SwStInvoiceXaztCheck;
import com.zdkj.subway.stm.enums.InvoiceCategoryEnum;
import com.zdkj.subway.stm.enums.InvoiceChechAuditTypeEnum;
import com.zdkj.subway.stm.enums.MessageEnums;
import com.zdkj.subway.stm.fegin.SupportService;
import com.zdkj.subway.stm.mapper.SwParamLineMapper;
import com.zdkj.subway.stm.mapper.SwParamStationMapper;
import com.zdkj.subway.stm.mapper.SwStInvoiceCatCheckMapper;
import com.zdkj.subway.stm.mapper.SwStPettymoneyCheckMapper;
import com.zdkj.subway.stm.service.SwStInvoiceCatCheckService;
import com.zdkj.subway.stm.service.SwStInvoiceXaztCheckService;
import com.zdkj.subway.stm.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 长安通定额发票盘点
 *
 * @author cxp
 * @date 2024-11-20 20:09:08
 */
@Service
@Slf4j
public class SwStInvoiceCatCheckServiceImpl extends ServiceImpl<SwStInvoiceCatCheckMapper, SwStInvoiceCatCheck> implements SwStInvoiceCatCheckService {
    private static final int MAX_RECURSION_DEPTH = 12;

    @Autowired
    private SwParamLineMapper swParamLineMapper;

    @Autowired
    private SwParamStationMapper swParamStationMapper;

	@Autowired
    private SwStPettymoneyCheckMapper swStPettymoneyCheckMapper;

    @Autowired
    private SwStInvoiceXaztCheckService swStInvoiceXaztCheckService;

    @Autowired
    private SupportService supportService;

    /**
     * 分页查询长安通定额发票盘点
     * @param page
     * @param swStInvoiceCatCheck
     * @return
     */
    @Override
    public IPage<SwStInvoiceCatCheck> page(Page page, SwStInvoiceCatCheck swStInvoiceCatCheck) {
        LambdaQueryWrapper<SwStInvoiceCatCheck> queryWrapper = Wrappers.query(swStInvoiceCatCheck).lambda();
        queryWrapper.orderByDesc(SwStInvoiceCatCheck::getStatisticsDate).orderByAsc(SwStInvoiceCatCheck::getStationCode);
        if(StrUtil.isNotBlank(swStInvoiceCatCheck.getStatisticsDateStr())) {
            queryWrapper.likeRight(SwStInvoiceCatCheck::getStatisticsDate, swStInvoiceCatCheck.getStatisticsDateStr());
        }
        if (!SecurityUtils.getUser().getBelongToLine()) {
            queryWrapper.eq(SwStInvoiceCatCheck::getLineCode, SecurityUtils.getUser().getLineCode());
            queryWrapper.eq(SwStInvoiceCatCheck::getStationCode, SecurityUtils.getUser().getStationCode());
        }
        // 查询长安通定额发票盘点
        IPage<SwStInvoiceCatCheck> resultPage = super.page(page, queryWrapper);
        List<SwStInvoiceCatCheck> records = new ArrayList<>(resultPage.getRecords());
        // 计算数量
        for (SwStInvoiceCatCheck record : records) {
            // 已使用数量
            Integer useNumber = CalculateUtil.sumOfNumbers(record.getUseTenNumber(), record.getUseTwentyNumber(), record.getUseFiftiyNumber(), record.getUseHundredNumber());
            // 已使用实点数量
            Integer useCheckNumber = CalculateUtil.sumOfNumbers(record.getUseTenCheckNumber(), record.getUseTwentyCheckNumber(), record.getUseFiftiyCheckNumber(), record.getUseHundredCheckNumber());
            // 已使用差异数量
            Integer useDiffNumber = CalculateUtil.sumOfNumbers(record.getUseTenDiffNumber(), record.getUseTwentyDiffNumber(), record.getUseFiftiyDiffNumber(), record.getUseHundredDiffNumber());
            // 未使用数量
            Integer unuseNumber = CalculateUtil.sumOfNumbers(record.getUnuseTenNumber(), record.getUnuseTwentyNumber(), record.getUnuseFiftiyNumber(), record.getUnuseHundredNumber());
            // 未使用实点数量
            Integer unuseCheckNumber = CalculateUtil.sumOfNumbers(record.getUnuseTenCheckNumber(), record.getUnuseTwentyCheckNumber(), record.getUnuseFiftiyCheckNumber(), record.getUnuseHundredCheckNumber());
            // 未使用差异数量
            Integer unuseDiffNumber = CalculateUtil.sumOfNumbers(record.getUnuseTenDiffNumber(), record.getUnuseTwentyDiffNumber(), record.getUnuseFiftiyDiffNumber(), record.getUnuseHundredDiffNumber());
            // 未使用部门配发数量
            Integer unuseDispatchNumber = CalculateUtil.sumOfNumbers(record.getUnuseTenDispatchNumber(), record.getUnuseTwentyDispatchNumber(), record.getUnuseFiftiyDispatchNumber(), record.getUnuseHundredDispatchNumber());
            // 未使用站间调配数量
            Integer unuseDeployNumber = CalculateUtil.sumOfNumbers(record.getUnuseTenDeployNumber(), record.getUnuseTwentyDeployNumber(), record.getUnuseFiftiyDeployNumber(), record.getUnuseHundredDeployNumber());
			 // 未使用上交数量
            Integer unuseDeployCompleteNumber = CalculateUtil.sumOfNumbers(record.getUnuseTenDeployCompleteNumber(), record.getUnuseTwentyDeployCompleteNumber(), record.getUnuseFiftiyDeployCompleteNumber(), record.getUnuseHundredDeployCompleteNumber());
            record.setUseNumber(useNumber);
            record.setUseCheckNumber(useCheckNumber);
            record.setUseDiffNumber(useDiffNumber);
            record.setUnuseNumber(unuseNumber);
            record.setUnuseCheckNumber(unuseCheckNumber);
            record.setUnuseDiffNumber(unuseDiffNumber);
            record.setUnuseDispatchNumber(unuseDispatchNumber);
            record.setUnuseDeployNumber(unuseDeployNumber);
			record.setUnuseDeployCompleteNumber(unuseDeployCompleteNumber);
        }
        resultPage.setRecords(records);
        return resultPage;
    }

    /**
     * 查询前一月盘点数据
     * @param checkTime
     * @param depth
     * @return
     */
    @Override
    public SwStInvoiceCatCheck getPreviousMonthInvoiceCatCheck(String checkTime, int depth) {
        // 递归MAX_RECURSION_DEPTH次后任无数据则直接返回
        if(depth > MAX_RECURSION_DEPTH) {
            return null;
        }
        PigxUser user = SecurityUtils.getUser();
        String previousMonth = DateUtilStm.getPreviousMonth(checkTime);
        LambdaQueryWrapper<SwStInvoiceCatCheck> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SwStInvoiceCatCheck::getLineCode, user.getLineCode())
                .eq(SwStInvoiceCatCheck::getStationCode, user.getStationCode())
                .likeRight(SwStInvoiceCatCheck::getStatisticsDate, previousMonth);
        List<SwStInvoiceCatCheck> invoiceCatCheckList = this.list(queryWrapper);
        if(CollectionUtil.isNotEmpty(invoiceCatCheckList)) {
            return invoiceCatCheckList.get(0);
        }
        // 递归查询，直至查询到上一个盘点月的数据
        return getPreviousMonthInvoiceCatCheck(previousMonth, depth + 1);
    }

    /**
     * 新增或修改车站长安通定额发票盘点
     * @param swStInvoiceCatCheck
     * @return
     */
    @Override
    public boolean saveOrUpdateInvoiceCatCheck(SwStInvoiceCatCheck swStInvoiceCatCheck) {
        PigxUser user = SecurityUtils.getUser();
        swStInvoiceCatCheck.setLineCode(user.getLineCode());
        swStInvoiceCatCheck.setStationCode(user.getStationCode());
        // 查询车站盘点日期的长安通定额发票盘点数据是否存在
        LambdaQueryWrapper<SwStInvoiceCatCheck> newStationincome = Wrappers.<SwStInvoiceCatCheck>lambdaQuery()
                .eq(SwStInvoiceCatCheck::getLineCode, swStInvoiceCatCheck.getLineCode())
                .eq(SwStInvoiceCatCheck::getStationCode, swStInvoiceCatCheck.getStationCode())
                .eq(SwStInvoiceCatCheck::getDelFlag, "0")
                .eq(SwStInvoiceCatCheck::getStatisticsDate, swStInvoiceCatCheck.getStatisticsDate());
        SwStInvoiceCatCheck stInvoiceCatCheck = this.getOne(newStationincome);
        // 重新计算数量和金额合计
        calculateAmount(swStInvoiceCatCheck);
        if (ObjectUtil.isNotEmpty(stInvoiceCatCheck)) {
            // 修改长安通定额发票盘点
            swStInvoiceCatCheck.setId(stInvoiceCatCheck.getId());
            return this.updateById(swStInvoiceCatCheck);
        }
        // 保存长安通定额发票盘点
        swStInvoiceCatCheck.setCheckStatus("0");
        return this.save(swStInvoiceCatCheck);
    }

    /**
     * 长安通定额发票盘点数据批量提交
     * @param ids
     * @param status
     * @return
     */
    @Override
    public boolean updateApprovalStatus(List<Integer> ids, String status, String auditType) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        List<SwStInvoiceCatCheck> updateData = new ArrayList<>();
        PigxUser user = SecurityUtils.getUser();
        for (Integer id : ids) {
			SwStInvoiceCatCheck stInvoiceCatCheck = this.getById(id);
			/*
			 SwStInvoiceCatCheck stInvoiceCatCheck = new SwStInvoiceCatCheck();
             stInvoiceCatCheck.setId(Long.valueOf(id));
			*/
            stInvoiceCatCheck.setCheckStatus(status);
            //SwStInvoiceCatCheck swStInvoiceCatCheck = baseMapper.selectById(id);
            QueryWrapper<SwParamStation> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CODE", stInvoiceCatCheck.getStationCode());
            SwParamStation swParamStation = swParamStationMapper.selectOne(queryWrapper);

            // 格式化日期
            LocalDate statisticsDate = stInvoiceCatCheck.getStatisticsDate();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
            String formattedDate = statisticsDate.format(formatter);

            SwMessageDTO swMessageDTO = new SwMessageDTO();
            swMessageDTO.setTitle(formattedDate+swParamStation.getName()+"长安通定额发票盘点数据审核");
            swMessageDTO.setMsgType("审批");
            swMessageDTO.setCreatorName(user.getNikeName());
            swMessageDTO.setCreatorId(user.getId());

			UpdateWrapper<SwStInvoiceCatCheck> updateWrapper=new UpdateWrapper<>();
            //盘点提交状态 0：未提交 1：已提交 2：车站驳回 3：车站审核通过 4.车间驳回 5.车间审核通过 6：部门驳回 7：部门审核通过
            if (status.equals("1")){
                swMessageDTO.setLineCode(stInvoiceCatCheck.getLineCode());
                swMessageDTO.setStationCode(stInvoiceCatCheck.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_APPROVAL_CAT_INVOICE_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZXZZ_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车站提交，站长待审核");
				//后续审核人员置空
				stInvoiceCatCheck.setAuditStationName("");
                stInvoiceCatCheck.setAuditStationJobNo("");  
				stInvoiceCatCheck.setAuditWorkshopName("");
                stInvoiceCatCheck.setAuditWorkshopJobNo("");
				stInvoiceCatCheck.setAuditDeptName("");
                stInvoiceCatCheck.setAuditDeptJobNo("");
				updateWrapper.set("AUDIT_STATION_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_WORKSHOP_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("2")){
                swMessageDTO.setLineCode(stInvoiceCatCheck.getLineCode());
                swMessageDTO.setStationCode(stInvoiceCatCheck.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_APPROVAL_CAT_INVOICE_STATUS_URL.getUrl());
                swMessageDTO.setContent("站长驳回");
				//后续审核人员置空
				stInvoiceCatCheck.setAuditWorkshopName("");
                stInvoiceCatCheck.setAuditWorkshopJobNo("");
				stInvoiceCatCheck.setAuditDeptName("");
                stInvoiceCatCheck.setAuditDeptJobNo("");
				updateWrapper.set("AUDIT_WORKSHOP_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            }else if (status.equals("3")){
                swMessageDTO.setDeptId(MessageEnums.WORKSHOP_DEPT_ID.getCode());//站务车间
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_APPROVAL_CAT_INVOICE_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZWPWGL_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("站长审核通过，车间票务专业待审核");
				updateWrapper.set("AUDIT_WORKSHOP_TIME", null); // 或者用lambda方式
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("4")) {
                swMessageDTO.setLineCode(stInvoiceCatCheck.getLineCode());
                swMessageDTO.setStationCode(stInvoiceCatCheck.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_APPROVAL_CAT_INVOICE_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZXZZ_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车间票务专业驳回，站长待审核");
				//后续审核人员置空				
				stInvoiceCatCheck.setAuditDeptName("");
                stInvoiceCatCheck.setAuditDeptJobNo("");
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("5")){
                swMessageDTO.setDeptId(MessageEnums.AUDIT_DEPT_ID.getCode());//安全技术室
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_APPROVAL_CAT_INVOICE_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.PWGLJSRY_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车间票务专业审核通过，部门票务专业待审核");
				updateWrapper.set("AUDIT_DEPT_TIME", null); // 或者用lambda方式
            } else if (status.equals("6")) {
                swMessageDTO.setDeptId(MessageEnums.WORKSHOP_DEPT_ID.getCode());//站务车间
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_APPROVAL_CAT_INVOICE_STATUS_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZWPWGL_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("部门票务专业驳回，车间票务专业待审核");

            }
            log.info("长安通定额发票盘点数据审核==>id:{},status:{},auditType:{},nikeName:{},time:{},oldStatus:{}", id, status,auditType,user.getNikeName(),new Date(),stInvoiceCatCheck.getCheckStatus());
            if (InvoiceChechAuditTypeEnum.AUDIT_STATION.getCode().equals(auditType)) { // 中心站长审核
                stInvoiceCatCheck.setAuditStationName(user.getNikeName());
                stInvoiceCatCheck.setAuditStationJobNo(user.getUserCode());
                stInvoiceCatCheck.setAuditStationTime(LocalDateTime.now());
				//后续审核人员置空
				stInvoiceCatCheck.setAuditWorkshopName("");
                stInvoiceCatCheck.setAuditWorkshopJobNo("");
				stInvoiceCatCheck.setAuditDeptName("");
                stInvoiceCatCheck.setAuditDeptJobNo("");
            } else if(InvoiceChechAuditTypeEnum.AUDIT_WORKSHOP.getCode().equals(auditType)) { // 车间票务专业审核
                stInvoiceCatCheck.setAuditWorkshopName(user.getNikeName());
                stInvoiceCatCheck.setAuditWorkshopJobNo(user.getUserCode());
                stInvoiceCatCheck.setAuditWorkshopTime(LocalDateTime.now());
				//后续审核人员置空
				stInvoiceCatCheck.setAuditDeptName("");
                stInvoiceCatCheck.setAuditDeptJobNo("");
            } else if(InvoiceChechAuditTypeEnum.AUDIT_DEPT.getCode().equals(auditType)) { // 部门票务专业审核
                stInvoiceCatCheck.setAuditDeptName(user.getNikeName());
                stInvoiceCatCheck.setAuditDeptJobNo(user.getUserCode());
                stInvoiceCatCheck.setAuditDeptTime(LocalDateTime.now());
            }
			 //updateData.add(stInvoiceCatCheck);
			//UpdateWrapper<SwStInvoiceCatCheck> updateWrapper=new UpdateWrapper<>();
			updateWrapper.eq("id", id);
			this.update(stInvoiceCatCheck, updateWrapper);
            supportService.saveInner(swMessageDTO, SecurityConstants.FROM_IN);
           
        }
        return true;//updateBatchById(updateData);
    }

    /**
     * 车站导出长安通定额发票盘点表
     * @param id
     * @param response
     */
    @Override
    public void exportInvoiceCatCheckForStation(Long id, HttpServletResponse response) {
        InputStream excelTemplate = null;
        if (ObjectUtil.isNotEmpty(id)) {
            SwStInvoiceCatCheck invoiceCatCheck = this.getById(id);
            try {
				
                // 格式化日期
                LocalDate statisticsDate = invoiceCatCheck.getStatisticsDate();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
                String formattedDate = statisticsDate.format(formatter);

				// 查询车站名称
                JSONObject jsonObject = getlinenameOrStationName(invoiceCatCheck.getLineCode(), invoiceCatCheck.getStationCode());
				String stationName = jsonObject.getString("stationName");

                response.reset(); // 非常重要
				response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");

				final String fileName = URLEncoder.encode("长安通冠名定额发票盘点表-"+stationName +"-" + formattedDate, "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                /*
                final String fileName = URLEncoder.encode("长安通冠名定额发票盘点表", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
                */
                excelTemplate = this.getClass().getResourceAsStream("/static/excel/template/SwStInvoiceCatCheckExcelTemplate.xlsx");

                ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplate).build();
                WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();

                Map<String, Object> map = BeanUtil.beanToMap(invoiceCatCheck);

                map.put("statisticsDate", formattedDate);
                
                map.put("stationName", stationName);
                // 生成流水号
                SerialNumberGenerator serialNumber = new SerialNumberGenerator();
                map.put("serialNumber", serialNumber.generateSerialNumber());

                excelWriter.fill(map, writeSheet);
                excelWriter.finish();
            }  catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(excelTemplate != null){
                    try {
                        excelTemplate.close();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }

                }
            }
        }
    }

	 /**
     * 车站导出长安通定额发票盘点表--多个车站多个sheet
     * @param checkTime 盘点日期
     * @param response
     */
    @Override
    public void exportInvoiceCatCheckForStationAll(String checkTime, HttpServletResponse response) {
        if (ObjectUtil.isNotEmpty(checkTime)) {            
			 // 查询要导出的车站备用金盘点数据
			LambdaQueryWrapper<SwStInvoiceCatCheck> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.apply("date_format(STATISTICS_DATE,'%Y-%m') = '" + checkTime+"'");
						
			queryWrapper.orderByDesc(SwStInvoiceCatCheck::getStatisticsDate).orderByAsc(SwStInvoiceCatCheck::getStationCode);
			List<SwStInvoiceCatCheck> records = this.list(queryWrapper);
			
            InputStream excelTemplateIs = null;
            try {

				//获取已有的车站数据
				Map<String,SwStInvoiceCatCheck> mapHaveData = new HashMap();
				String formattedDate = "";
               
				if(records!=null && records.size()>0){
					
				   SwStInvoiceCatCheck data0 = records.get(0);
					// 格式化日期
                   LocalDate statisticsDate = data0.getStatisticsDate();
				  
                   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月");
                   formattedDate = statisticsDate.format(formatter);
				}
				records.forEach(item -> {
					// 查询车站名称
					JSONObject jsonObject = getlinenameOrStationName(item.getLineCode(), item.getStationCode());
					//设置盘点时间改为年月
					item.setStatisticsDateStr(DateUtilStm.localDateToString(item.getStatisticsDate(),"yyyy-MM"));
					item.setStationCode(jsonObject.getString("stationName"));
                   	mapHaveData.put(jsonObject.getString("stationName"),item); //key车站名字
			   });
				
              
                response.reset(); // 非常重要
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");

				final String fileName = URLEncoder.encode("长安通冠名定额发票盘点表(全部车站)-" + formattedDate, "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
                /*
                final String fileName = URLEncoder.encode("长安通冠名定额发票盘点表", "UTF-8");
                response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
                */
                excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/SwStInvoiceCatCheckAllStationExcelTemplate.xlsx");
                ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
			    
				List<Map<String,String>> stationMap = swStPettymoneyCheckMapper.selectStationMap();        
               //车站循环,每个车站对应一个对象，为导出做准备
			   int i=0;//计数器，创建了多少个Sheet
			   for (Map<String,String> mapStations : stationMap) {
					String stationCode = mapStations.get("CODE");
					String stationName = mapStations.get("NAME");                    
					 i++;
					 SwStInvoiceCatCheck entityExport = new SwStInvoiceCatCheck();
					 boolean isExist = false;
					 if(mapHaveData!=null){
					    if(mapHaveData.containsKey(stationName)){
							isExist =true;
							entityExport = mapHaveData.get(stationName);                            
					    }
					}
					if(!isExist){
						entityExport.setStatisticsDateStr(formattedDate);					    
					}
					entityExport.setStationCode(stationName);
					
					Map<String, Object> map = BeanUtil.beanToMap(entityExport);
                    map.put("statisticsDate", formattedDate);
                    map.put("stationName", stationName);					
					WriteSheet writeSheet = EasyExcel.writerSheet(i-1,stationName).build();                   
                    excelWriter.fill(map,writeSheet);					
				 }

                excelWriter.finish();				
            }  catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(excelTemplateIs != null){
                    try {
                        excelTemplateIs.close();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }

                }
            }
        }
    }

    /**
     * 审核页面导出长安通定额发票和西安中铁定额发票盘点
     * @param swStInvoiceCheckDTO
     * @param response
     */
    @Override
    public void exportInvoiceCatCheckForApproval(SwStInvoiceCheckDTO swStInvoiceCheckDTO, HttpServletResponse response) {
        // 导出日期范围
        String statisticsDate = swStInvoiceCheckDTO.getStatisticsDate();
        // 导出车站集合
        List<String> stationCodes = swStInvoiceCheckDTO.getStationCodes();
        // 导出发票类别集合
        String invoiceCategory = swStInvoiceCheckDTO.getInvoiceCategory();
        boolean exportAll = InvoiceCategoryEnum.ALL_INVOICE.getCode().equals(invoiceCategory);
        List<SwStInvoiceCatCheck> invoiceCatCheckDatas = new ArrayList<>();
        List<SwStInvoiceXaztCheck> invoiceXaztCheckDatas = new ArrayList<>();
        // 查询要导出的长安通定额发票盘点数据
        List<SwStInvoiceCatCheck> invoiceCatCheckRecords = getInvoiceCatCheckRecords(statisticsDate, stationCodes);
        // 查询要导出的西安中铁定额发票盘点数据
        List<SwStInvoiceXaztCheck> invoiceXaztCheckRecords = swStInvoiceXaztCheckService.getInvoiceXaztCheckRecords(statisticsDate, stationCodes);
        if (CollectionUtil.isEmpty(invoiceCatCheckRecords) && CollectionUtil.isEmpty(invoiceXaztCheckRecords)) {
            return;
//            throw new RuntimeException("没有可导出的数据！");
        }
        if (InvoiceCategoryEnum.ALL_INVOICE.getCode().equals(invoiceCategory)) {
            invoiceCatCheckDatas = invoiceCatCheckRecords;
            invoiceXaztCheckDatas = invoiceXaztCheckRecords;
        } else if (InvoiceCategoryEnum.CAT_INVOICE.getCode().equals(invoiceCategory)) {
            invoiceCatCheckDatas = invoiceCatCheckRecords;
        } else if (InvoiceCategoryEnum.XAZT_INVOICE.getCode().equals(invoiceCategory)) {
            invoiceXaztCheckDatas = invoiceXaztCheckRecords;
        }

        try {

            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("冠名定额发票盘点表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + statisticsDate + fileName + DateUtilStm.getNowDayString("yyyy-MM-dd") + ".xlsx");

            Map<String, Map<LocalDate, List<Integer>>> processedData = new LinkedHashMap<>();
            // 处理长安通盘点数据
            Map<String, Map<LocalDate, List<Integer>>> invoiceCatCheckData = processData(invoiceCatCheckDatas);
            // 处理西安中铁盘点数据
            Map<String, Map<LocalDate, List<Integer>>> invoiceXaztCheckData = swStInvoiceXaztCheckService.processData(invoiceXaztCheckDatas);
            if (InvoiceCategoryEnum.ALL_INVOICE.getCode().equals(invoiceCategory)) {
                // 合并长安通和西安中铁盘点数据
                mergeMap(processedData, invoiceCatCheckData, invoiceXaztCheckData);
            } else if (InvoiceCategoryEnum.CAT_INVOICE.getCode().equals(invoiceCategory)) {
                processedData.putAll(invoiceCatCheckData);
            } else if (InvoiceCategoryEnum.XAZT_INVOICE.getCode().equals(invoiceCategory)) {
                processedData.putAll(invoiceXaztCheckData);
            }

            // 生成最终数据
            List<List<Object>> data = generateData(processedData, invoiceCategory);

            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("盘点数据");
            ExcelUtilsStm.seettingColumnWidth(sheet);

            // 创建单元格样式
            CellStyle centeredCellStyle = ExcelUtilsStm.createCenteredCellStyle(workbook);
            CellStyle borderCellStyle = ExcelUtilsStm.createBorderCellStyle(workbook);
            CellStyle wrappedHeaderStyle = ExcelUtilsStm.createWrappedHeaderStyle(workbook);

            // 格式化日期
            String formatDate = getFormatDate(statisticsDate);
            String monthStr = getMonth(statisticsDate);

            // 写入盘点日期
            Row dateRow = sheet.createRow(0);
            dateRow.setHeightInPoints(35);
            Cell dateCell = dateRow.createCell(0);
            dateCell.setCellValue("盘点日期: " + formatDate);
            // 创建并配置单元格样式
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setBorderRight(BorderStyle.THIN);
            dateCell.setCellStyle(cellStyle);
            CellRangeAddress cellRangeAddr = new CellRangeAddress(0, 0, 0, 6);  //代表 行0到行0  列0到列5，如果增加列需要改数字5
            sheet.addMergedRegion(cellRangeAddr);
            // 应用边框颜色（可选）
            RegionUtil.setBorderBottom(BorderStyle.THIN, cellRangeAddr, sheet);
            RegionUtil.setBorderTop(BorderStyle.THIN, cellRangeAddr, sheet);
            RegionUtil.setBorderLeft(BorderStyle.THIN, cellRangeAddr, sheet);
            RegionUtil.setBorderRight(BorderStyle.THIN, cellRangeAddr, sheet);

            // 写入表头
            Row headerRow = sheet.createRow(1);
            headerRow.setHeightInPoints(35);
            String[] headers = {"车站", "发票类型及面额", monthStr + "月部门配发数量", monthStr + "月站间调配数量", monthStr + "月上交数量", monthStr + "月已使用实点数量", monthStr + "月未使用实点数量"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(wrappedHeaderStyle);
            }

            // 写入数据
            int rowIndex = 2;
            for (List<Object> row : data) {
                Row dataRow = sheet.createRow(rowIndex++);
                for (int i = 0; i < row.size(); i++) {
                    Cell cell = dataRow.createCell(i);
                    Object value = row.get(i);
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof String) {
                        cell.setCellValue((String) value);
                    }
                    cell.setCellStyle(borderCellStyle); // 设置边框
                    if (i != 1) {
                        cell.setCellStyle(centeredCellStyle); // 设置居中样式和边框
                    }
                }
            }

            // 合并车站行
            int stationRowIndex = 2;
            for (Map.Entry<String, Map<LocalDate, List<Integer>>> entry : processedData.entrySet()) {
                sheet.addMergedRegion(new CellRangeAddress(stationRowIndex, stationRowIndex + (exportAll ? 7 : 3), 0, 0));
                stationRowIndex += (exportAll ? 8 : 4);
            }

            // 输出 Excel 文件
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("导出长安通定额发票和西安中铁定额发票盘点点数据失败");
        }
    }

    /**
     * 查询要导出的长安通定额发票盘点数据
     * @param statisticsDate
     * @param stationCodes
     * @return
     */
    private List<SwStInvoiceCatCheck> getInvoiceCatCheckRecords(String statisticsDate, List<String> stationCodes) {
        LambdaQueryWrapper<SwStInvoiceCatCheck> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(statisticsDate)) {
            wrapper.likeRight(SwStInvoiceCatCheck::getStatisticsDate, statisticsDate);
        }
        if (ObjectUtil.isNotEmpty(stationCodes)) {
            wrapper.in(SwStInvoiceCatCheck::getStationCode, stationCodes);
        }
        //wrapper.orderByDesc(SwStInvoiceCatCheck::getStatisticsDate);
		wrapper.orderByDesc(SwStInvoiceCatCheck::getStatisticsDate).orderByAsc(SwStInvoiceCatCheck::getStationCode);		
        List<SwStInvoiceCatCheck> list = this.list(wrapper);
        list.forEach(item -> {
            // 查询车站名称
            JSONObject jsonObject = getlinenameOrStationName(item.getLineCode(), item.getStationCode());
            item.setStationName(jsonObject.getString("stationName"));
        });
        return list;
    }

    /**
     * 处理长安通盘点数据
     * @param invoiceCatCheckList
     * @return
     */
    private Map<String, Map<LocalDate, List<Integer>>> processData(List<SwStInvoiceCatCheck> invoiceCatCheckList) {
        Map<String, Map<LocalDate, List<Integer>>> processedData = new LinkedHashMap<>();
        for (SwStInvoiceCatCheck invoiceCatCheck : invoiceCatCheckList) {
            String station = invoiceCatCheck.getStationName();
            LocalDate statisticsDate = invoiceCatCheck.getStatisticsDate();

            if (!processedData.containsKey(station)) {
                processedData.put(station, new HashMap<>());
            }

            Map<LocalDate, List<Integer>> stationData = processedData.get(station);
            if (!stationData.containsKey(statisticsDate)) {
                stationData.put(statisticsDate, new ArrayList<>(Collections.nCopies(20, 0)));
            }

            List<Integer> monthData = stationData.get(statisticsDate);
            monthData.set(0, invoiceCatCheck.getUnuseTenDispatchNumber());
            monthData.set(1, invoiceCatCheck.getUnuseTenDeployNumber());
			monthData.set(2, invoiceCatCheck.getUnuseTenDeployCompleteNumber());
            monthData.set(3, invoiceCatCheck.getUseTenCheckNumber());
            monthData.set(4, invoiceCatCheck.getUnuseTenCheckNumber());
            monthData.set(5, invoiceCatCheck.getUnuseTwentyDispatchNumber());
            monthData.set(6, invoiceCatCheck.getUnuseTwentyDeployNumber());
			monthData.set(7, invoiceCatCheck.getUnuseTwentyDeployCompleteNumber());
            monthData.set(8, invoiceCatCheck.getUseTwentyCheckNumber());
            monthData.set(9, invoiceCatCheck.getUnuseTwentyCheckNumber());
            monthData.set(10, invoiceCatCheck.getUnuseFiftiyDispatchNumber());
            monthData.set(11, invoiceCatCheck.getUnuseFiftiyDeployNumber());
			monthData.set(12, invoiceCatCheck.getUnuseFiftiyDeployCompleteNumber());
            monthData.set(13, invoiceCatCheck.getUseFiftiyCheckNumber());
            monthData.set(14, invoiceCatCheck.getUnuseFiftiyCheckNumber());
            monthData.set(15, invoiceCatCheck.getUnuseHundredDispatchNumber());
            monthData.set(16, invoiceCatCheck.getUnuseHundredDeployNumber());
			monthData.set(17, invoiceCatCheck.getUnuseHundredDeployCompleteNumber());
            monthData.set(18, invoiceCatCheck.getUseHundredCheckNumber());
            monthData.set(19, invoiceCatCheck.getUnuseHundredCheckNumber()); 
			//Excel内要导出的数据值
        }
        return processedData;
    }

    /**
     * 生成最终导出数据
     * @param processedData
     * @param invoiceCategory
     * @return
     */
    private List<List<Object>> generateData(Map<String, Map<LocalDate, List<Integer>>> processedData, String invoiceCategory) {
        boolean exportAll = InvoiceCategoryEnum.ALL_INVOICE.getCode().equals(invoiceCategory);
        List<List<Object>> data = new ArrayList<>();
        // 生成最终数据
        for (Map.Entry<String, Map<LocalDate, List<Integer>>> entry : processedData.entrySet()) {
            String station = entry.getKey();
            Map<LocalDate, List<Integer>> stationData = entry.getValue();

            // 发票类型
            String[] allDenominations = {"长安通10元", "长安通20元", "长安通50元", "长安通100元", "定额2元", "定额3元", "定额4元", "定额10元"};
            String[] catDenominations = {"长安通10元", "长安通20元", "长安通50元", "长安通100元"};
            String[] xaztDenominations = {"定额2元", "定额3元", "定额4元", "定额10元"};

            // 填充数据行
            for (int denominationIndex = 0; denominationIndex < (exportAll ? 8 : 4); denominationIndex++) {
                List<Object> dataRow = new ArrayList<>();
                dataRow.add(station);
                if (InvoiceCategoryEnum.ALL_INVOICE.getCode().equals(invoiceCategory)) {
                    dataRow.add(allDenominations[denominationIndex]);
                } else if (InvoiceCategoryEnum.CAT_INVOICE.getCode().equals(invoiceCategory)) {
                    dataRow.add(catDenominations[denominationIndex]);
                } else if (InvoiceCategoryEnum.XAZT_INVOICE.getCode().equals(invoiceCategory)) {
                    dataRow.add(xaztDenominations[denominationIndex]);
                }
                LocalDate date = LocalDate.of(2025, 1, 1); // 初始值，稍后替换
                for (LocalDate d : stationData.keySet()) {
                    date = d;
                }
                List<Integer> monthData = stationData.getOrDefault(date, Collections.nCopies((exportAll ? 40 : 20), 0));  //4列时是32,16
                int index = denominationIndex * 5;  //原来是4列
                dataRow.add(monthData.get(index));
                dataRow.add(monthData.get(index + 1));
                dataRow.add(monthData.get(index + 2));
                dataRow.add(monthData.get(index + 3));
				dataRow.add(monthData.get(index + 4)); // 原来是4列，没有此行
                data.add(dataRow);
            }
        }

        return data;
    }

    /**
     * 数量和金额计算
     * @param swStInvoiceCatCheck
     */
    private void calculateAmount(SwStInvoiceCatCheck swStInvoiceCatCheck) {
        // 10元未使用金额合计
        BigDecimal unuseTenMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUnuseTenNumber()).orElse(0) * 10);
        // 20元未使用金额合计
        BigDecimal unuseTwentyMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUnuseTwentyNumber()).orElse(0) * 20);
        // 50元未使用金额合计
        BigDecimal unuseFiftiyMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUnuseFiftiyNumber()).orElse(0) * 50);
        // 100元未使用金额合计
        BigDecimal unuseHundredMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUnuseHundredNumber()).orElse(0) * 100);

        // 10元未使用差异数量
        int unuseTenDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUnuseTenCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUnuseTenNumber()).orElse(0);
        // 20元未使用差异数量
        int unuseTwentyDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUnuseTwentyCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUnuseTwentyNumber()).orElse(0);
        // 50元未使用差异数量
        int unuseFiftiyDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUnuseFiftiyCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUnuseFiftiyNumber()).orElse(0);
        // 100元未使用差异数量
        int unuseHundredDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUnuseHundredCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUnuseHundredNumber()).orElse(0);

        swStInvoiceCatCheck.setUnuseTenMoney(unuseTenMoney);
        swStInvoiceCatCheck.setUnuseTwentyMoney(unuseTwentyMoney);
        swStInvoiceCatCheck.setUnuseFiftiyMoney(unuseFiftiyMoney);
        swStInvoiceCatCheck.setUnuseHundredMoney(unuseHundredMoney);
        swStInvoiceCatCheck.setUnuseTenDiffNumber(unuseTenDiffNumber);
        swStInvoiceCatCheck.setUnuseTwentyDiffNumber(unuseTwentyDiffNumber);
        swStInvoiceCatCheck.setUnuseFiftiyDiffNumber(unuseFiftiyDiffNumber);
        swStInvoiceCatCheck.setUnuseHundredDiffNumber(unuseHundredDiffNumber);

        // 10元使用金额合计
        BigDecimal useTenMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUseTenNumber()).orElse(0) * 10);
        // 20元使用金额合计
        BigDecimal useTwentyMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUseTwentyNumber()).orElse(0) * 20);
        // 50元使用金额合计
        BigDecimal useFiftiyMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUseFiftiyNumber()).orElse(0) * 50);
        // 100元使用金额合计
        BigDecimal useHundredMoney = BigDecimal.valueOf(Optional.ofNullable(swStInvoiceCatCheck.getUseHundredNumber()).orElse(0) * 100);

        // 10元使用差异数量
        int useTenDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUseTenCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUseTenNumber()).orElse(0);
        // 20元使用差异数量
        int useTwentyDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUseTwentyCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUseTwentyNumber()).orElse(0);
        // 50元使用差异数量
        int useFiftiyDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUseFiftiyCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUseFiftiyNumber()).orElse(0);
        // 100元使用差异数量
        int useHundredDiffNumber = Optional.ofNullable(swStInvoiceCatCheck.getUseHundredCheckNumber()).orElse(0) - Optional.ofNullable(swStInvoiceCatCheck.getUseHundredNumber()).orElse(0);

        swStInvoiceCatCheck.setUseTenMoney(useTenMoney);
        swStInvoiceCatCheck.setUseTwentyMoney(useTwentyMoney);
        swStInvoiceCatCheck.setUseFiftiyMoney(useFiftiyMoney);
        swStInvoiceCatCheck.setUseHundredMoney(useHundredMoney);
        swStInvoiceCatCheck.setUseTenDiffNumber(useTenDiffNumber);
        swStInvoiceCatCheck.setUseTwentyDiffNumber(useTwentyDiffNumber);
        swStInvoiceCatCheck.setUseFiftiyDiffNumber(useFiftiyDiffNumber);
        swStInvoiceCatCheck.setUseHundredDiffNumber(useHundredDiffNumber);
    }

    /**
     * 获取线路名称&车站名称
     * @param lineCode
     * @param stationCode
     * @return
     */
    public JSONObject getlinenameOrStationName(String lineCode, String stationCode) {
        JSONObject object = new JSONObject();
        QueryWrapper<SwParamLine> queryWrapperLine = new QueryWrapper<>();
        queryWrapperLine.lambda().eq(SwParamLine::getCode, lineCode);
        List<SwParamLine> swParamLines = swParamLineMapper.selectList(queryWrapperLine);
        if (CollectionUtil.isNotEmpty(swParamLines)) {
            lineCode = swParamLines.get(0).getCode();
            object.put("lineName", swParamLines.get(0).getName());
            QueryWrapper<SwParamStation> queryWrapperStation = new QueryWrapper<>();
            queryWrapperStation.lambda().eq(SwParamStation::getLineCode, lineCode)
                    .eq(SwParamStation::getCode, stationCode);
            List<SwParamStation> swParamStations = swParamStationMapper.selectList(queryWrapperStation);
            if (CollectionUtil.isNotEmpty(swParamStations)) {
                object.put("stationName", swParamStations.get(0).getName());
            }
        }
        return object;
    }

    /**
     * 合并连个map的数据
     * @param processedData
     * @param invoiceCatCheckData
     * @param invoiceXaztCheckData
     */
    private void mergeMap(Map<String, Map<LocalDate, List<Integer>>> processedData, Map<String, Map<LocalDate, List<Integer>>> invoiceCatCheckData, Map<String, Map<LocalDate, List<Integer>>> invoiceXaztCheckData) {
        // 获取所有唯一的日期
        Set<LocalDate> allDates = new HashSet<>();
        for (Map<String, Map<LocalDate, List<Integer>>> map : Arrays.asList(invoiceCatCheckData, invoiceXaztCheckData)) {
            for (Map<LocalDate, List<Integer>> innerMap : map.values()) {
                allDates.addAll(innerMap.keySet());
            }
        }
        // 最大长度
        int maxLength = 16;
        // 处理每个键
        for (String key : invoiceCatCheckData.keySet()) {
            Map<LocalDate, List<Integer>> mergedInnerMap = new HashMap<>();
            for (LocalDate date : allDates) {
                List<Integer> list1 = invoiceCatCheckData.getOrDefault(key, new HashMap<>()).get(date);
                List<Integer> list2 = invoiceXaztCheckData.getOrDefault(key, new HashMap<>()).get(date);

                // 如果 list1 或 list2 为 null，则创建一个全 0 的列表
                if (list1 == null) {
                    list1 = Collections.nCopies(maxLength, 0);
                } else {
                    while (list1.size() < maxLength) {
                        list1.add(0);
                    }
                }
                if (list2 == null) {
                    list2 = Collections.nCopies(maxLength, 0);
                } else {
                    while (list2.size() < maxLength) {
                        list2.add(0);
                    }
                }

                // 合并两个列表
                List<Integer> mergedList = new ArrayList<>(list1);
                mergedList.addAll(list2);
                mergedInnerMap.put(date, mergedList);
            }
            processedData.put(key, mergedInnerMap);
        }
    }

    /**
     * 截取字符串
     * @param s
     * @return
     */
    private String getLastTwoChars(String s) {
        if (s == null || s.length() < 2) {
            return s; // 如果字符串为空或长度小于2，则返回原字符串
        } else {
            return s.substring(s.length() - 2);
        }
    }

    /**
     * 获取日期
     * @param dateStr YYYY-MM
     * @return YYYY年M月
     */
    public static String getFormatDate(String dateStr) {
        if (dateStr == null || !dateStr.matches("\\d{4}-\\d{2}")) {
            throw new IllegalArgumentException("日期格式无效");
        }
        String year = dateStr.substring(0, 4);
        String month = dateStr.substring(5);
        month = month.startsWith("0") ? month.substring(1) : month;
        return year + "年" + month + "月";
    }

    /**
     * 获取月份
     * @param dateStr YYYY-MM
     * @return M
     */
    public String getMonth(String dateStr) {
        if (dateStr == null || !dateStr.matches("\\d{4}-\\d{2}")) {
            throw new IllegalArgumentException("日期格式无效");
        }
        String month = dateStr.substring(5);
        return month.startsWith("0") ? month.substring(1) : month;
    }
}
